﻿using S7.Net;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WindowsServiceDemo1
{
    public partial class Service1 : ServiceBase
    {
        private Plc siemens;
        private CancellationTokenSource cts;
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                this.siemens = new Plc(CpuType.S71500, "192.168.0.20", 0, 1);
                this.siemens.Open();
                cts = new CancellationTokenSource();
                Task.Run(async () =>
                {
                    while (!cts.IsCancellationRequested)
                    {
                        try
                        {
                            for (int i = 0; i < 100; i++)
                            {
                                this.siemens.Write("DB100.DBD0", (float)++i);
                                this.siemens.Write("DB100.DBD4", (float)(i + 10.3));
                                await Task.Delay(1000);
                                WriteInfo("写PLC数据： 瞬时流量：" + (++i).ToString("f2") + " kg/h" + " 累计流量：" + (i + 10.3).ToString("f2"));
                            }



                        }
                        catch (Exception ex)
                        {
                            WriteInfo(ex.Message);
                        }


                    }
                    this.siemens.Close();

                });
            }
            catch (Exception ex)
            {
                WriteInfo(ex.Message);
            }
        }
        private string filepath = "H:\\ServiceLog.txt";
        private void WriteInfo(string info)
        {
            using (FileStream stream = new FileStream(filepath, FileMode.Append))
            {
                using (StreamWriter write = new StreamWriter(stream))
                {
                    write.WriteLine($"{DateTime.Now}, {info}");
                }
            }
        }

        protected override void OnStop()
        {
            this.siemens?.Close();
        }
    }
}
